package com.gitee.urick.union.builder;

import com.gitee.urick.union.config.UnionConfig;
import com.gitee.urick.union.template.UnionDocBuilderTemplate;
import com.power.common.util.FileUtil;
import com.power.doc.builder.ProjectDocConfigBuilder;
import com.power.doc.model.ApiDoc;
import com.power.doc.template.IDocBuildTemplate;
import com.power.doc.utils.BeetlTemplateUtil;
import com.thoughtworks.qdox.JavaProjectBuilder;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.Template;

import java.util.List;

import static com.gitee.urick.union.constants.UnionConstants.UNION_ONE_SEARCH_TPL;
import static com.gitee.urick.union.constants.UnionConstants.UNION_OUT_HTML_DIR;
import static com.power.doc.constants.DocGlobalConstants.*;

/**
 * @author Rick 2021/02/08
 * @since 1.0
 */
public class UnionHtmlBuilder {
    private static String INDEX_HTML = "index.html";

    /**
     * build handler api
     *
     * @param config config
     */
    public static void buildApiDoc(UnionConfig config) {
        JavaProjectBuilder javaProjectBuilder = new JavaProjectBuilder();
        buildApiDoc(config, javaProjectBuilder);
    }

    /**
     * Only for smart-doc maven plugin and gradle plugin.
     *
     * @param config             ApiConfig
     * @param javaProjectBuilder ProjectDocConfigBuilder
     */
    public static void buildApiDoc(UnionConfig config, JavaProjectBuilder javaProjectBuilder) {
        UnionDocDataBuilder builderTemplate = new UnionDocDataBuilder();
        config.setParamsDataToTree(false);
        config.setHtml(true);
        builderTemplate.checkAndInit(config);
        ProjectDocConfigBuilder configBuilder = new ProjectDocConfigBuilder(config, javaProjectBuilder);
        IDocBuildTemplate<ApiDoc> docBuildTemplate = new UnionDocBuilderTemplate();
        List<ApiDoc> apiDocList = docBuildTemplate.getApiData(configBuilder);
        Template indexCssTemplate = BeetlTemplateUtil.getByName(UNION_OUT_HTML_DIR + ALL_IN_ONE_CSS);
        FileUtil.nioWriteFile(indexCssTemplate.render(), config.getOutPath() + FILE_SEPARATOR + ALL_IN_ONE_CSS);
        if (StringUtils.isNotEmpty(config.getAllInOneDocFileName())) INDEX_HTML = config.getAllInOneDocFileName();
        builderTemplate.buildAllInOne(apiDocList, config, javaProjectBuilder, UNION_OUT_HTML_DIR + ALL_IN_ONE_HTML_TPL, INDEX_HTML);
        builderTemplate.buildSearchJs(apiDocList, config, javaProjectBuilder, UNION_OUT_HTML_DIR + UNION_ONE_SEARCH_TPL);
    }
}
